<template>
    <div class="box">
        <el-upload
            v-model:file-list="fileList"
            ref="uploadRef"
            :action="props.url"
            list-type="picture-card"
            :data="props.data"
            :headers="{ token: getToken('token') }"
            :before-remove="beforeDelUp"
            :on-preview="onImgView"
            :limit="props.limit"
            :on-success="success"
            accept
            name="files"
            :auto-upload="props.autoUpload"
        >
            <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div> 
</template>

<script lang="ts" setup>
import { ref, onBeforeMount } from 'vue'
import { get } from '@/http/axios'
import type { UploadInstance, UploadUserFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from "../utils/local"
interface Props{
    id:number
    url:string
    limit:number
    imgPrefix:string    //图片地址前缀
    autoUpload:boolean
    data: object
    getImgUrl?:string
}
const props = defineProps<Props>()
const uploadRef = ref<UploadInstance>()
const dialogVisible = ref<boolean>(false)   //是否展示弹出层
const dialogImageUrl = ref<string>('')      //弹出层中的图片地址
const emit = defineEmits<{
    (e:'delImg',name:string):boolean
    (e:'success'):void
}>()

onBeforeMount(() => {
    getImg()
})
const fileList = ref<UploadUserFile[]>([])
const submitUpload = () => {
  uploadRef.value!.submit()
}
function onImgView(uploadFile) {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}
function success(){
    //uploadRef.value!.clearFiles()
    if (props.autoUpload) {
        ElMessage.success('上传成功')
    }
    emit('success')
}
function beforeDelUp(file:File){
    ElMessageBox.confirm(
    '您确定删除这张图片吗？','提醒',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      draggable: true,
    }).then(() => {
        emit('delImg',file.name)
    }).catch(() => {
      ElMessage({
        type: 'warning',
        message: '删除取消',
      })
      
    })
    return false
}
function getImg() {
    if (!props.getImgUrl) return
    get(props.getImgUrl).then(res => {   
        console.log('查看图片信息',res);
             
        if (!res.result.length) return
        res.result.forEach(el => {
            fileList.value?.push({ name:el, url: props.imgPrefix + el })
        })
    })
}
defineExpose({
    submitUpload,
    fileList
})
</script>

<style lang="scss" scoped>
.box{
    width: 100%;
    height: 100%;
    display: flex;
    justify-items: start;
    align-items: start;
}
</style>